package com.dlwx.firefighting.fragment;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dlwx.firefighting.MainActivity;
import com.dlwx.firefighting.R;
import com.dlwx.firefighting.activity.SearchActivity;
import com.dlwx.firefighting.activity.VideoDetailActivity;
import com.dlwx.firefighting.adapter.VideoAdapter;
import com.dlwx.firefighting.bean.VideoBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.utils.glide.GlideImageLoaderForBanner;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 学习视频fragment
 */
public class VideoFragment extends Fragment {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.title_right_one_btn)
    ImageView titleRightOneBtn;
    @BindView(R.id.video_recyclerview)
    LRecyclerView videoRecyclerview;
    Unbinder unbinder;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<VideoBean> datas = new ArrayList<>();
    private VideoAdapter videoAdapter;
    Banner banner;
    private boolean isRefresh;

    private int page=1;
    private int requestNum=10;
    private int count=0;
    private int catId=0;

    public VideoFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_video, container, false);
        unbinder = ButterKnife.bind(this, view);
        getBanner();
        getDatas();
        initView();
        return view;
    }

    private void getDatas( ) {
        DialogUtils.showProgressDlg(getActivity(),"");
        OkGo.<String>post(Constant.STUDYLIST)
                .tag(this)
                .params("cat_id", catId)
                .params("num", requestNum)
                .params("page", page)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult = new DealResult();
//                        List<VideoBean> beans = dealResult.deal(getActivity(), response, new TypeToken<BaseBean<VideoBean>>() {
//                        }.getType());
//                        if(isRefresh){
//                            videoAdapter.clear();
//                        }
//                        videoAdapter.addAll(beans);
//                        videoRecyclerview.refreshComplete(requestNum);
//                        count=videoAdapter.getItemCount();
                    }
                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


    public void initView() {
        tvMiddleTitle.setText("学习中心");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        videoAdapter = new VideoAdapter(getActivity());
        videoRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        videoAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(videoAdapter);
        videoRecyclerview.setAdapter(lRecyclerViewAdapter);
        videoRecyclerview.setPullRefreshEnabled(true);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.divider_height)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_gray)
                .build();
        videoRecyclerview.addItemDecoration(divider);
        initHeader();
        videoRecyclerview.setPullRefreshEnabled(false);
        videoRecyclerview.setLoadMoreEnabled(true );
       /* //设置下拉刷新
        mainRecyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                adapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
            }
        });*/
        videoRecyclerview.refresh();
        //设置上拉加载更多
        videoRecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (count < (page * requestNum)) {
                    ToastUtils.toastForShort(getActivity(), getString(R.string.no_more));
                    videoRecyclerview.setNoMore(true);
                } else {
                    isRefresh=false;
                    page++;
                    getDatas();
                }
            }
        }
             );
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                Intent i=new Intent(getActivity(), WebActivity.class);
                Intent i=new Intent(getActivity(), VideoDetailActivity.class);
                i.putExtra("id",videoAdapter.getDataList().get(position).getVideo_id());
                startActivity(i);
            }
        });

    }

    //创建header
    private void initHeader() {
        CommonHeader header = new CommonHeader(getActivity(), R.layout.groupon_video_header);
        banner = (Banner) header.findViewById(R.id.groupon_header_banner);
        final TextView videoAllTv = (TextView) header.findViewById(R.id.video_all);
        final TextView videoVideoTv = (TextView) header.findViewById(R.id.video_video);
        final TextView videoVoiceTv = (TextView) header.findViewById(R.id.video_voice);
        int gcolor=0;
        int rcolor=0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            gcolor=getActivity().getResources().getColor(R.color.main_theme_color,getActivity().getTheme());
            rcolor=getActivity().getResources().getColor(R.color.second_textcolor,getActivity().getTheme());
        }else{
            gcolor=getActivity().getResources().getColor(R.color.main_theme_color);
            rcolor=getActivity().getResources().getColor(R.color.second_textcolor);
        }
        lRecyclerViewAdapter.addHeaderView(header);

        final int greenColor = gcolor;
        final int greyColor = rcolor;
        videoAllTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page=1;
                catId=0;
                isRefresh=true;
               /* videoAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();*/
                getDatas();
                videoAllTv.setTextColor(greenColor);
                videoVideoTv.setTextColor(greyColor);
                videoVoiceTv.setTextColor(greyColor);
            }
        });
        videoVideoTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page=1;
                catId=1;
                isRefresh=true;
               /* videoAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();*/
                getDatas();
                videoAllTv.setTextColor(greyColor);
                videoVideoTv.setTextColor(greenColor);
                videoVoiceTv.setTextColor(greyColor);
            }
        });
        videoVoiceTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page=1;
                catId=2;
                isRefresh=true;
               /* videoAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();*/
                getDatas();
                videoAllTv.setTextColor(greyColor);
                videoVideoTv.setTextColor(greyColor);
                videoVoiceTv.setTextColor(greenColor);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void getBanner() {
        OkGo.<String>post(Constant.BANNER)
                .tag(this)
             /*   （1、首页banner 2、商城banner3、学习中心banner）*/
                .params("position_id",3)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult result=new DealResult();
//                        List<String> beans=result.deal(getActivity(),response,new TypeToken<BaseBean<String>>(){}.getType());
//                        initBanner(beans);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                    }
                });
    }

    private void initBanner(List<String> beans) {
        if(beans.isEmpty()){
            return;
        }
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoaderForBanner());
        banner.setImages(beans);
        banner.start();
    }

    @OnClick({R.id.title_left_one_btn, R.id.title_right_one_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                MainActivity mainActivity= (MainActivity) getActivity();
                mainActivity.onKeyDown(KeyEvent.KEYCODE_BACK, null);
                break;
            case R.id.title_right_one_btn:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }
}
